package com.sl.eurekaserver.controller;

import java.util.Observable;
import java.util.Observer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import rx.Subscriber;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.ObservableExecutionMode;
import com.sl.eurekaserver.entity.User;

/**
 * 注解的方式实现发布订阅模式
 * 
 * @author 舒莉
 *
 */
@RestController
public class AnnoUserObservableController {
	
	@Autowired
	private RestTemplate restTemplate;

	@SuppressWarnings({ "deprecation", "rawtypes" })
	@HystrixCommand(
			ignoreExceptions={Exception.class},
			observableExecutionMode = ObservableExecutionMode.EAGER)
	public rx.Observable getUserById(String userName) {
		// 创建事件起源
		return rx.Observable.create(new rx.Observable.OnSubscribe<User>() {

			public void call(Subscriber<? super User> observer) {
				try {
					if (!observer.isUnsubscribed()) {
						User user = restTemplate.getForObject(
								"http://HELLO-SERVICE/hello/{userName}",
								User.class, userName);
						observer.onNext(user);
						observer.onCompleted();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

}
